package com.maezia.tdr.dao.repository;

import com.maezia.tdr.common.CommonConstant;
import com.maezia.tdr.common.redis.BaseRedisRepository;
import com.maezia.tdr.dao.mapper.ClientDetailsMapper;
import com.maezia.tdr.domain.po.ClientDetails;
import com.maezia.tdr.domain.po.Dict;
import com.maezia.tdr.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

@Repository
public class ClientDetailsRepository extends BaseRedisRepository<ClientDetails> {

    private static String CLIENT_DETAILS_INFO_KEY = "CLIENT_DETAILS";

    @Autowired
    private ClientDetailsMapper clientDetailsMapper;

    @Autowired
    private DictService dictService;

    public ClientDetailsRepository() {
        super(ClientDetails.class);
    }

    public void save(ClientDetails clientDetails){
        String redisKey = CLIENT_DETAILS_INFO_KEY + CommonConstant.COLON + clientDetails.getClientId();
        if(!redisTemplateTemporary.hasKey(redisKey)){
            Dict dict = dictService.getByKey(CLIENT_DETAILS_INFO_KEY);
            redisValueOpsTemporary.set(redisKey, clientDetails, Long.valueOf(dict.getValue()), TimeUnit.DAYS);
        }
    }

    public ClientDetails getByClientId(String clientId) {
        String redisKey = CLIENT_DETAILS_INFO_KEY + CommonConstant.COLON + clientId;
        ClientDetails clientDetails = redisValueOpsTemporary.get(redisKey);
        if(ObjectUtils.isEmpty(clientDetails)){
            clientDetails = clientDetailsMapper.getByClientId(clientId);
            if(!ObjectUtils.isEmpty(clientDetails)){
                save(clientDetails);
            }
        }
        return clientDetails;
    }
}
